<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Exception;
use app\common\service\DbfService;
use app\common\service\SysLogService;

class Ocrbatch extends Controller
{
    /**
     * 处理文档
     * 
     * @return string JSON格式的处理结果
     */
    public function processdocument()
    {
        try {
            // 获取请求参数
             $data = request()->param();
    
            // 参数验证
            if (empty($data['name'])) {
                return $this->jsonResponse(400, '名称不能为空');
            }
            
            if (empty($data['filePath'])) {
                return $this->jsonResponse(400, '文件路径不能为空');
            }
            
            $name = $data['name'];
            
            $directoryPath = $data['filePath'];

            // 检查目录是否存在
            if (!is_dir($directoryPath)) {
                return $this->jsonResponse(404, '目录不存在: ' . $directoryPath);
            }

            $filePath = $data ['dbfPath'];
            // 检查文件是否存在
            if (!file_exists($filePath)) {
                return $this->jsonResponse(404, 'DBF文件不存在: ' . $filePath);
            }

            // 路径替换掉获取相对路径
           

            // 开始事务
            Db::startTrans();
            
            try {
                // 创建任务记录
                $insertOcrTask = [
                    "name" => $name,
                    "file_path" => $filePath,
                    "create_time" => date("Y-m-d H:i:s"),
                    "status" => 0,
                    "path" => $directoryPath,
                    "update_time" => date("Y-m-d H:i:s"),
                    "is_delete" => 0,
                 ];



                $taskId = Db::name('zstp_article_task')->insertGetId($insertOcrTask);

                if (!$taskId) {
                    throw new Exception('创建任务记录失败');
                }
                
                // 读取DBF文件
                $dbfService = new DbfService();
                // 注意： 如果DbfService的readDbf方法不再接受taskId参数，需要在下面修改调用方式
                $result = $dbfService->readDbf($filePath, $taskId);

        if ($result['code'] !== 200) {
                    throw new Exception($result['message']);
        }

                $list = $result['data'];

                if (empty($list)) {
                    throw new Exception('DBF文件中没有有效数据');
                }
                
                // 批量插入数据
                $insertResult = Db::table('zstp_article_ocr')->insertAll($list);
                
                if ($insertResult === false) {
                    throw new Exception('插入文章数据失败');
                }
                
                // 更新任务状态为已完成
                Db::name('zstp_article_task')->where('id', $taskId)->update([
      
                    'update_time' => date("Y-m-d H:i:s")
                ]);


                // 添加日志
                $sysLogService = new SysLogService();
                $result =  $sysLogService->addLog('添加批处理任务('.$name.')', $taskId, 1, '任务id:'.$taskId); 
                
                // 提交事务
                Db::commit();

                
   
                return $this->jsonResponse(200, "成功处理 " . count($list) . " 条记录");
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                throw $e;
            }
        } catch (Exception $e) {
            // 捕获所有异常
            return $this->jsonResponse(500, '处理失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 输出JSON格式的响应
     * 
     * @param int $code 状态码
     * @param string $message 消息
     * @param array $data 数据
     * @return string
     */
    protected function jsonResponse($code, $message, $data = [])
    {
        return json_encode([
            'code' => $code,
            'message' => $message,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
    }


    
    
    public function getTaskList(){

        $data = request()->post();
        $page = isset($data['page']) ? intval($data['page']) : 1;
        $limit = isset($data['limit']) ? intval($data['limit']) : 10;
        
        $map = [];
        $map['is_delete'] = ['=', '0'];
        
        // 如果有搜索条件，可以在这里添加
        if (isset($data['name']) && !empty($data['name'])) {
            $map['name'] = ['like', '%' . $data['name'] . '%'];
        }
        
        if (isset($data['qzh']) && !empty($data['qzh'])) {
            $map['qzh'] = ['=', $data['qzh']];
        }
        
        if (isset($data['status']) && $data['status'] !== '') {
            $map['status'] = ['=', intval($data['status'])];
        } 
        
        // 获取总数
        $count = Db::table('zstp_processdocument_task')
            ->where($map)
            ->count();
            
        // 获取分页数据
        $list = Db::table('zstp_processdocument_task')
            ->where($map)
            ->page($page, $limit)
            ->order('create_time desc')
            ->select();
            
        return json([
            'code' => 200,
            'message' => '获取成功',
            'data' => [
                'total' => $count,
                'items' => $list,
                'page' => $page,
                'limit' => $limit
            ]
        ]);

        
    
    }



}
